// 运行时配置

import { LogoutOutlined, LockOutlined, SettingOutlined } from '@ant-design/icons';
import { RunTimeLayoutConfig } from '@umijs/max';
import { Dropdown, message } from 'antd';
import React, { useState } from 'react';
import { CONFIG } from './constants/config';
import { logout } from './services/auth';
// import ResetPasswordModal from './components/ResetPasswordModal';
import { api } from '@/services/api';

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const token = localStorage.getItem(CONFIG.CACHE.TOKEN_KEY);
    if (!token) {
      return undefined;
    }

    // 从后端重新获取最新的用户信息
    const userInfo = await api.accounts.accountsUsersMeRetrieve();
    
    // 更新本地存储的用户信息
    localStorage.setItem(
      CONFIG.CACHE.USER_INFO_KEY,
      JSON.stringify(userInfo),
    );

    return {
      ...userInfo
    };
  } catch (error) {
    console.error('获取用户信息失败:', error);
    return undefined;
  }
};

// 全局初始化数据配置
export async function getInitialState() {
  // 如果是登录页面，不执行
  if (location.pathname === '/login') {
    return {
      settings: {
        title: CONFIG.SYSTEM.NAME,
      },
    };
  }

  const currentUser = await fetchUserInfo();

  // 如果没有用户信息，重定向到登录页
  if (!currentUser && location.pathname !== '/login') {
    window.location.href = '/login';
    return {
      settings: {
        title: CONFIG.SYSTEM.NAME,
      },
    };
  }

  return {
    currentUser,
    settings: {
      title: CONFIG.SYSTEM.NAME,
    },
  };
}

// 运行时布局配置
export const layout: RunTimeLayoutConfig = ({ initialState }) => {
  const [resetPasswordVisible, setResetPasswordVisible] = useState(false);

  return {
    logo: 'https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg',
    menu: {
      locale: false,
    },
    layout: 'mix',
    splitMenus: true,
    fixedHeader: true,
    avatarProps: initialState?.currentUser ? {
      src: 'https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png',
      size: 'small',
      title: initialState.currentUser.username,
      render: (props, dom) => (
        <>
          <Dropdown
            menu={{
              items: [
                {
                  key: 'settings',
                  icon: <SettingOutlined />,
                  label: '系统设置',
                  onClick: () => {
                    window.location.href = '/system/settings';
                  },
                },
                // {
                //   key: 'reset-password',
                //   icon: <LockOutlined />,
                //   label: '重置密码',
                //   onClick: () => setResetPasswordVisible(true),
                // },
                {
                  type: 'divider',
                },
                {
                  key: 'logout',
                  icon: <LogoutOutlined />,
                  label: '退出登录',
                  onClick: async () => {
                    try {
                      const success = await logout();
                      if (success) {
                        localStorage.removeItem(CONFIG.CACHE.USER_INFO_KEY);
                        localStorage.removeItem(CONFIG.CACHE.TOKEN_KEY);
                        localStorage.removeItem(CONFIG.CACHE.REFRESH_TOKEN_KEY);
                        localStorage.removeItem(CONFIG.CACHE.DEVICE_ID_KEY);
                        window.location.href = '/login';
                      } else {
                        message.error('登出失败，请重试');
                      }
                    } catch (error) {
                      console.error('登出出错:', error);
                      message.error('登出失败，请重试');
                    }
                  },
                },
              ],
            }}
          >
            {dom}
          </Dropdown>
          {/* <ResetPasswordModal
            visible={resetPasswordVisible}
            onCancel={() => setResetPasswordVisible(false)}
          /> */}
        </>
      ),
    } : undefined,
    // 页面加载时，获取用户信息
    onPageChange: async () => {
      const { pathname } = location;
      // 如果没有登录，重定向到 login
      if (!initialState?.currentUser && pathname !== '/login') {
        window.location.href = '/login';
      }
    },
  };
};
